<?php
class HomeController extends AppController {
	var $name = 'Home';
	var $helpers = array('Html', 'Form', 'Javascript', 'Cache', 'Time', 'Ajax','Tinymce','Util');
 	var $components = array('Readini','Auth');
 	var $uses = array('Category','User','Image','Album', 'Pagee', 'Product', 'Brand', 'Order', 'OrderProduct','Messenger','Banner','Uploadfile');
    var $paginate = array('limit'=>15);
    var $layout = 'home_page';
    
    //Message error
    var $messError = '<h2>Error found</h2>
				<p>We have found some error on your request, please try to refresh your browser. or <a href="/frontpages/contact_us">contact us</a> for further information</p>
				<p>Sorry for any inconvenient
				</p>
				<p>You can also <a href="/">click here</a> to go to homepage or <a href="javascript:history.go(-1)">click here</a> to go back to previous page</p>';
	
	
	function beforeFilter()
	{
		parent::beforeFilter();
		$this->Auth->allow('*'); // allow everybody access/ comment it for permission implement
	}
	
	function index()
	{
		$this->Product->recursive = -1;
		
		// get newest product
		$condition_newest['Product.is_new = '] = '1';
		$newestProduct = $this->Product->find('all',array('conditions' => $condition_newest,'limit' => 4 ,'order' => 'created_date DESC'));
		
		// get  hostest product
		$condition_hotest['Product.is_hot = '] = '1';
		$hotestProduct = $this->Product->find('all',array('conditions' => $condition_hotest,'limit' => 4 ,'order' => 'created_date DESC'));
		
		$this->set('newestProduct', $newestProduct);
		$this->set('hotestProduct', $hotestProduct);
		
		$banners = $this->Banner->find('all');
		$this->set('banners',$banners);
	}
	
	function ym() {
		$mess = $this->Messenger->find('all');
			if (isset($this->params['requested'])) {
				return $mess;
			}
		}
	
	function downloadfiles (){
		$uploadfile = $this->Uploadfile->find('first');
//		debug($uploadfile); die();
			if (isset($this->params['requested'])) {
				return $uploadfile;
			}
		}
		
	function advs()
	{
		$advs = $this->Adventisement->paginate('Product',array('Limit'=>'5', 'ORDER BY'=>'orders'));		
		return $advs;
	}
	function product_category($id = null)
	{
		$this->Category->recursive = 1;
		
		$categories_condition = "Category.level = 1";
		$categories = $this->Category->find('all',array('conditions' => $categories_condition));
		if (isset($this->params['requested'])) {
					return $categories;
		}
		
	    if ($id)
	    {
			$this->paginate = array('Product' => array(	'limit' => 5));
	    	$category = $this->Category->findById($id);
	    	if (isset($category['Category']['id']))
	    	{
	    		$condition['Category.root_path LIKE'] = $category['Category']['root_path'].'%';
	    	}
	    	$this->set('category', $category['Category']['name']);
	    }
	    else
	    {
	    	$condition = '';
	    	$this->set('category', 'Sản phẩm');
	    }
	    
	    if (!empty($this->passedArgs))
	    {
	    	if(isset($this->passedArgs['Seach.Price']))
	    	{
	    		
	    		$chars = preg_split('/-/', $this->passedArgs['Seach.Price'], -1, PREG_SPLIT_OFFSET_CAPTURE);
	    		//debug($chars);
	    		//die();
	    		$condition = 'Product.price >= '. $chars[0][0] .'000000 AND Product.price <= '. $chars[1][0] .'000000';
	    		$this->set('category', 'Tìm kiếm');
	    	}
	    	
	    }
	    
	    $this->set('products',$this->paginate('Product',array( $condition )));
		$this->set('id', $id);
		//gan bien session de dua vao layout (khi load cac trang khac thi style cua element category_menu van giu duoc nhu cu)
		$_SESSION['c_id'] = $id;
	}
	function menu()
	{
		$this->Category->recursive = -1;
		$this->Brand->recursive = -1;
		
		$data = array('categories'=>$this->Category->findAll(), 'brands'=>$this->Brand->findAll());

		if (isset($this->params['requested'])) 
		{
			return $data;
		}
	}
	/*
	 * Xay dung may tinh
	 */
	function customize()
	{
		$condition['Category.root_path LIKE'] = '1:%';
		$condition['Category.level >'] = '1';
		$this->paginate = array('order' => 'Category.orders DESC');
		$categories = $this->paginate('Category',array($condition));
		$this->set('categories', $categories);
		
		if(isset($_REQUEST['listProduct']))
		{
			//$this->set('sumary',10);
			$listProductId = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", $_REQUEST['listProduct'], 0, PREG_SPLIT_DELIM_CAPTURE);
			$sum = 0;
			foreach ($listProductId as $productId)
			{
				$this->Product->recursive = -1;
				$product = $this->Product->findById($productId);
				$sum += $product['Product']['price'];
			}
			$this->set('sumary', $sum);
		}
		else
		{
			$this->set('sumary',0);
		}
		
	}
	
	function download(){
		$data = $_POST['data']['Product']['product_id'];
//		debug($data); die();
		
		// Láº¥y ra list cÃ¡c product
		$listProductId = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", $data, 0, PREG_SPLIT_DELIM_CAPTURE);
//		debug($listProductId); die();
		$products = array();
		$prices = 0;
		$i = 0;
		foreach($listProductId as $productId)
		{
			if($productId!=0)
			{
				$products[$i] = $this->Product->findById($productId);
				$prices += $products[$i]['Product']['price'];
				$i++;
			}
		}
		$this->set('products', $products);
		//debug($products); die();
		$this->set('Price', $prices);
//		debug($_POST); die();
	}
	
	function getPrice($data = null)
	{
		$products = preg_split(':', $data);
		if (isset($this->params['requested'])) {
					return $categories;
		}
	}
	/*
	 * Trang chi tiáº¿t sáº£n pháº©m
	 */
	function product($id = null)
	{
		$this->Product->recursive = 1;
		
	    if ($id)
	    {
	    	$products = $this->Product->findById($id);
	    	$this->set('product', $products);
	    }
	    else
	    {
	    	//redirect to home
	    }
	}
	/*
	 * Trang báº£o hÃ nh
	 */
	function warranty()
	{
		$page = $this->Pagee->find("Pagee.title like '%bảo hành%'");
		$this->set('pages',$page);
	}
	/*
	 * Trang giá»›i thiá»‡u dá»‹ch vá»¥
	 */
	function services()
	{
		$page = $this->Pagee->find("Pagee.title like '%dịch vụ%'");
		$this->set('pages',$page);
	}
	function introduction()
	{
		$page = $this->Pagee->find("Pagee.title like '%giới thiệu%'");
		$this->set('pages',$page);
	}
	function career()
	{
		$page = $this->Pagee->find("Pagee.title like '%tuyển dụng%'");
		$this->set('pages',$page);
	}
	/*
	 * Trang liÃªn há»‡
	 */
	function contact()
	{}
	/*
	 * Giá»� hÃ ng
	 */
	function shoppingcart()
	{
		
	}
	
	function order($data=null)
	{
		$data = $_POST["data"];
		// Láº¥y ra list cÃ¡c product
		$listProductId = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", $data['Order']['products'], 0, PREG_SPLIT_DELIM_CAPTURE);
		$sum = 0;
		foreach ($listProductId as $productId)
		{
			$this->Product->recursive = -1;
			$product = $this->Product->findById($productId);
			$sum += $product['Product']['price'];
		}
		$data['Order']['sumary'] = $sum;
		$data['Order']['created_date'] = strtotime(date('Y-m-d h:m:s'));
		// Loáº¡i pháº§n tá»­ products ra khá»�i máº£ng
		unset($data['Order']['products']);		
		// sá»­ lÃ½ dá»¯ liá»‡u, biáº¿n products thÃ nh máº£ng
		
		// Insert order
		if($this->Order->save($data))
		{
			$oder_id = $this->Order->getLastInsertId();
			
			foreach ($listProductId as $productId)
			{
				if($productId != 0)
				{
					$order_product["OrderProduct"]["order_id"] = $oder_id;
					$order_product["OrderProduct"]["product_id"] = $productId;
					$order_product["OrderProduct"]["quantity"] = 1;
					$this->OrderProduct->save($order_product);
				}
			}
			$this->Session->setFlash (__ ('Thêm mới thành công', true));
		}
		$this->redirect (array('action' => 'index'));
	}
	function orderpreview()
	{
		Configure::write('debug', 0);
		$this->layout= '';
		$data = $_POST["products"];
		
		
		// Láº¥y ra list cÃ¡c product
		$listProductId = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|[\s,]+/", $data, 0, PREG_SPLIT_DELIM_CAPTURE);
		$products = array();
		$prices = 0;
		$i = 0;
		foreach($listProductId as $productId)
		{
			if($productId!=0)
			{
				$products[$i] = $this->Product->findById($productId);
				$prices += $products[$i]['Product']['price'];
				$i++;
			}
		}
		$this->set('products', $products);
		$this->set('Price', $prices);
	}
	function contactus()
	{
		$filename = WWW_ROOT . 'config/common.ini';
		$this->data = $this->Readini->read($filename);
	}
	function submitContact(){
		$filename = WWW_ROOT . 'config/common.ini';
		$info = $this->Readini->read($filename);
		
		$Headers = "From: ".$this->data['Home']['fullname']. "<".$this->data['Home']['email'].">"."\r\nReply-To: ".$this->data['Home']['email']; 
		$emailto = $info['Company']['email'];
		$content = 	 $this->data['Home']['content']."\n"		
					.$this->data['Home']['fullname']."\n"
					.$this->data['Home']['tel']."\n"
					.$this->data['Home']['email'];
		$title = "Contact From TonyComputer : ";
		mail($emailto,$title,$content,$Headers);
		$this->redirect('/home/index');
	}
	function test(){
		
		function get_random_color()
		{
			$c='';
		    for ($i = 0; $i<6; $i++)
		    {
		        $c .=  dechex(rand(0,15));
		    }
		    return "$c";
		}
		
		$captcha = get_random_color();
		$captcha_url = '';
		
		if( !isset($_SESSION['dCaptchaContentb']) || !isset($_REQUEST['captcha']))
		{
			$_SESSION['dCaptchaContentb'] = $captcha;
			$captcha_url = '/gen.php?text='.$captcha;
		}
		else if(isset($_REQUEST['captcha']))
		{
			if($_SESSION['dCaptchaContentb'] == $_REQUEST['captcha'])
			{
				echo 'OKE';
			}
			else
			{
				//noproccess
				echo 'ERROR';
			}
			unsset($_SESSION['dCaptchaContentb']);
		}
		
		$this->set('captcha_image', $captcha_url);
	}
}
?>